package com.jp.knowledge.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.client.android.CaptureActivity;
import com.iflytek.cloud.SpeechError;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.adapter.FragMentAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.ComPopuWindow;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.VoiceInputUtils;
import com.jp.knowledge.view.CommViewPage;
import com.jp.knowledge.view.HomePageView;
import com.jp.knowledge.view.HomePagerHeaderRecycerView;
import com.jp.knowledge.view.ItemView;
import com.jp.knowledge.view.TabView;
import com.jp.knowledge.view.TopItemView;
import com.jp.knowledge.view.behavior.UCViewHeaderBehavior;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;

import static android.R.attr.width;

/**
 * Created by jiayen on 16/9/26.
 */
public class ToutiaoFragment extends BaseFragment implements ResultSubscriber.OnResultListener, View.OnClickListener, CommNewsFragment.RefreshListener {

    /**
     * 获取导航标识
     */
    private final int HEAD_LINE_CODE = 0x01;
    private final int REQUEST_RECORD_AUDIO_CODE = 0x02;
    private final int REQUEST_CAMERA_CODE = 0x03;
    private final int QR_SCAN_CODE = 0x04;
    private final int HEAD_LINE_UPDATE = 0x05;


    protected ImageView rightIcon;
    protected View contentView;
    private TopItemView itemViews;
    private LinearLayout itemContentView;
    protected Context mContext;
    private View headTopView;
    private CommViewPage viewPage;
    private TabView tabView;

    protected List<Fragment> fragments;
    private ImageView shaiXuan;//筛选

    private int itemTemWidth;//临时使用宽度

    protected List<String> tabNames;
    protected String[] items = null;// new String[]{"推荐","产品","公司","人物","在用","经历","方案","报告","PM","设计","技术","市场","运营","管理","资本","职场","创业","游戏","活动","业界","资讯","竞报",};
    protected List<HeadLine> headLines;
    protected FragMentAdapter fragmentAdapter;

    private ComPopuWindow window;
    private RelativeLayout headLayout;
    private HomePageView homePageView;
    private UCViewHeaderBehavior headerBehavior;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView =  inflater.inflate(R.layout.toutiao_fragment, null);
        mContext = getActivity();
        tabNames = new ArrayList<>();
        if (headLines != null && headLines.size() > 0) {
            initHeadStr(headLines.size());
            init();
        } else {
            DBHelper.getInstance().findAll(HeadLine.class, new Subscriber<List<HeadLine>>() {
                @Override
                public void onCompleted() {

                }
                @Override
                public void onError(Throwable e) {
                    getHeadLine();
                }

                @Override
                public void onNext(List<HeadLine> heads) {
                    headLines = heads;
                    if (headLines != null && headLines.size() > 0) {
                        initHeadStr(headLines.size());
                        init();
                    } else {
                        getHeadLine();
                    }
                }
            });
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            View topBar = contentView.findViewById(R.id.head_layout);
//            int statusBarHeight = 0;
//            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//            if (resourceId > 0)
//                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
//            topBar.setPadding(0, statusBarHeight, 0, 0);
//        }
        return contentView;
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        window=null;
        super.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_CODE && grantResults.length > 0){
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
                ToasUtil.toast(mContext, "抱歉，你没有权限访问打开麦克风，请到设置中开启麦克风权限后重试");
            else
                openVoiceInput();
        } else if(requestCode == REQUEST_CAMERA_CODE && grantResults.length > 0){
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
                ToasUtil.toast(mContext, "抱歉，你没有权限访问打开摄像头，请到设置中开启摄像头权限后重试");
            else
                scanQR();
        }
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode==QR_SCAN_CODE && resultCode==10001) {            //二维码返回
            String url = data.getStringExtra("url");
            ToasUtil.toast(mContext,url);
        }
    }

    protected void init() {

        initHead(contentView);
        setHeadInfo();




        headTopView = contentView.findViewById(R.id.head_line_show);
        headLayout = (RelativeLayout) contentView.findViewById(R.id.head_layout);

        rightIcon = (ImageView) contentView.findViewById(R.id.icon_serach);
        rightIcon.setVisibility(View.VISIBLE);
        contentView.findViewById(R.id.module_name).setVisibility(View.GONE);
        contentView.findViewById(R.id.module_desc).setVisibility(View.GONE);
        contentView.findViewById(R.id.icon_left).setVisibility(View.VISIBLE);
        contentView.findViewById(R.id.text_left).setVisibility(View.VISIBLE);
        ((ImageView)contentView.findViewById(R.id.icon_left)).setImageResource(R.mipmap.headlines_icon);
        ((TextView)contentView.findViewById(R.id.text_left)).setText("今日知识");

        itemViews = (TopItemView) contentView.findViewById(R.id.items_content);
        viewPage = (CommViewPage) contentView.findViewById(R.id.content_page);
        tabView = (TabView) contentView.findViewById(R.id.tab_view);
        itemContentView = itemViews.getContentView();
        itemViews.addItems(items);

        shaiXuan = (ImageView) contentView.findViewById(R.id.shaixuan);
        shaiXuan.setOnClickListener(this);

        int size = items.length;
        fragments = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            CommNewsFragment fragment = new CommNewsFragment();
            fragment.newInstance(headLines.get(i).getTypeId());
            fragment.setRefreshListener(this);
            fragments.add(fragment);
        }

        tabNames.clear();
        for(int i = 0; i < items.length; i++)
            tabNames.add(items[i]);
        fragmentAdapter = new FragMentAdapter(getFragmentManager(), fragments);
        viewPage.setAdapter(fragmentAdapter);
        tabView.setupWithViewPager(viewPage);
        tabView.setTabItems(tabNames);
        viewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int width = itemViews.getItemWidth(position);
                if (width == 0) {
                    width = itemTemWidth;
                }

                int[] itemPosition = itemViews.getItemPositionOnWindow(position);
                int[] ScrollViewStart = new int[2];
                itemViews.getLocationInWindow(ScrollViewStart);
                int startXDistance = itemPosition[0]-ScrollViewStart[0];
                int endXDistance = ScrollViewStart[0]+itemViews.getWidth()-itemPosition[0];
                if(startXDistance < 0) {
                    itemViews.smoothScrollBy(startXDistance, 0);
                }else if(endXDistance < width){
                    itemViews.smoothScrollBy(width-endXDistance, 0);
                }
                itemViews.selectedCur(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        itemViews.setOnItemChangeListener(new TopItemView.ItemChangeListerner() {
            @Override
            public void done(ItemView itemView, int position) {
                viewPage.setCurrentItem(position);
            }
        });

        rightIcon.setOnClickListener(this);

        homePageView = ((HomePagerHeaderRecycerView) contentView
                .findViewById(R.id.home_page_view)).getHomePageView();
        homePageView.setHomePageViewCallback(new HomePageView.HomePageViewCallback() {
            @Override
            public void onVoiceInputClick() {
                openVoiceInput();
            }
            @Override
            public void onQRCodeScanfClick() {
                scanQR();
            }
            @Override
            public void onWatchMoreClick() {
                if(headerBehavior != null)
                    headerBehavior.closePager();
            }
            @Override
            public void refreshData(){
                CommNewsFragment currentFragment = (CommNewsFragment) fragments.get(viewPage.getCurrentItem());
                String typeId = currentFragment.getTypeId();
                homePageView.setTag(typeId);
                currentFragment.onRefresh();
            }
        });
        headerBehavior = (UCViewHeaderBehavior) ((CoordinatorLayout.LayoutParams)contentView
                .findViewById(R.id.news_view_header_layout).getLayoutParams()).getBehavior();
        headerBehavior.setOnBebaviorListener(new UCViewHeaderBehavior.OnBebaviorListener() {
            @Override
            public void onBebaviorOpen() {
                setNestedScroll(false);
                if(bebaviorListener != null)
                    bebaviorListener.onBebaviorOpen();
            }
            @Override
            public void onBebaviorClose() {
                setNestedScroll(true);
                if(bebaviorListener != null)
                    bebaviorListener.onBebaviorClose();
            }
        });
        setNestedScroll(false);
        homePageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                closeHeader();
            }
        }, 300);
    }

    /**
     * 设置头部信息
     */
    private void setHeadInfo() {
        topDesc.setText("一路同行的头条");
    }

    /**
     * 初始化fragments
     */
    private void initFragments() {
        initHeadStr(headLines.size());
        itemViews.updateItem(items);
        int size = items.length;
        fragments = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            CommNewsFragment fragment = new CommNewsFragment();
            fragment.newInstance(headLines.get(i).getTypeId());
            fragments.add(fragment);
        }
        fragmentAdapter.updateFragments(fragments, headLines);
        for(int i = 0; i < items.length; i++)
            tabNames.add(items[i]);
        setNestedScroll(false);
    }

    private void setNestedScroll(boolean isClose){
        viewPage.setSwapSwitchEnable(isClose);
        ((CommNewsFragment) fragments.get(viewPage.getCurrentItem())).setRefreshEnabled(isClose);
        ((CommNewsFragment) fragments.get(viewPage.getCurrentItem())).setLoadMoreEnabled(isClose);
        ((CommNewsFragment) fragments.get(viewPage.getCurrentItem())).showTipAfterGetData(isClose);
        ((CommNewsFragment) fragments.get(viewPage.getCurrentItem())).setCanFling(isClose);
    }

    private void getHeadLine() {
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("type", 12);
        HttpHelper.getInstance(mContext).getHeadLine(param, HEAD_LINE_CODE, this);
    }

    private void openVoiceInput(){
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            && (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)){
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_CODE);
        } else {
            VoiceInputUtils.getInstance(mContext).startInput(new VoiceInputUtils.VoiceInputCallback() {
                @Override
                public void onResult(String result) {
                    if (result.trim().length() > 0)
                        SearchActivity.gotoSearch(mContext, result, 0);
                }
                @Override
                public void onChanged(String str) {}
                @Override
                public void onError(SpeechError speechError) {}
            });
        }
    }

    /* 扫描二维码 */
    private void scanQR(){
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                && (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)){
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_CODE);
        } else{
            startActivityForResult(new Intent(mContext, CaptureActivity.class), QR_SCAN_CODE);
        }
    }

    @Override
    public void onStart(int requestType) {
        L.d("onstart");
    }

    @Override
    public void onCompleted(int requestType) {
        L.d("onCompleted");
    }

    @Override
    public void onError(int requestType) {
        L.d("onError");
    }

    @Override
    public void onNext(IModel t, int requestType) {
        if (requestType == HEAD_LINE_CODE && t.getErrcode() == 0) {
           List<HeadLine> temp = t.getList(HeadLine.class);
//            if(temp!=null&&temp.size()>0){
//                if(headLines==null||headLines.size()==0){
//                    headLines=temp;
//                }else{
//                    // 插入新的
//                    for (HeadLine line : temp)
//                        if(!headLines.contains(line))
//                            headLines.add(line);
//                    // 移除没有的
//                    List<HeadLine> newHeadLines = new ArrayList<>();
//                    for(HeadLine headLine : headLines)
//                        if(temp.contains(headLine))
//                            newHeadLines.add(headLine);
//                    headLines = newHeadLines;
//                }
//            }

            headLines=temp;
            if (headLines != null && headLines.size() > 0) {
                int size = headLines.size();
                initHeadStr(size);
            }
            init();
            sureSortHead();
        } else if(requestType == HEAD_LINE_UPDATE){

        }
    }

    /**
     * 初始化headline值
     *
     * @param size
     */
    private void initHeadStr(int size) {
        items = new String[size];
        for (int i = 0; i < size; i++) {
            items[i] = headLines.get(i).getTypeName();
        }
    }

    /**
     * 保存到数据库
     *
     * @param headLines
     */
    protected void saveDb(final  List<HeadLine> headLines) {
        DBHelper.getInstance().delete(HeadLine.class);
        DBHelper.getInstance().save(headLines);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shaixuan:
                sortHead();
                break;
            case R.id.sure:
                sureSortHead();
                break;
            case R.id.icon_serach:
                Intent intent =new Intent(mContext, SearchActivity.class);
                intent.putExtra("action",1);
                intent.putExtra("level",0);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void sureSortHead() {
        if (headLines != null && headLines.size() > 0)
            saveDb(headLines);
        initFragments();
    }

    /**
     * 排序数据
     */
    private void sortHead() {
        if (window == null) {
            window = new ComPopuWindow(getActivity());
            window.setOnItemListerner(new OnItemListerner() {
                @Override
                public void onItemClick(View view, int position) {
                    itemTemWidth = itemContentView.getChildAt(position).getMeasuredWidth();
                    L.e("sortHead------width=" + width);
                    window.dismiss();
                    viewPage.setCurrentItem(position);
                }
            });
            window.setDragItemHelper(new ComPopuWindow.DragItemHelper() {
                @Override
                public void drag(int fromPosition, int toPosition) {

//                    排序数据
                    HeadLine headLine = headLines.remove(fromPosition);
                    headLines.add(toPosition, headLine);
                }

                @Override
                public void dragFinish() {

                }
            });
            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
//                        headLines = window.getHeadLine();
                    sureSortHead();

                    JsonObject param = new JsonObject();
                    param.addProperty("type", 12);
                    param.add("data", new Gson().toJsonTree(headLines, new TypeToken<List<HeadLine>>() {}.getType()).getAsJsonArray());
                    HttpHelper.getInstance(mContext).headLineUpdate(param, HEAD_LINE_UPDATE, ToutiaoFragment.this);
                }
            });
        }
        window.showPopupWindow(headTopView, headLines);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (headLines != null && headLines.size() > 0)
//            saveDb(headLines);//保存当前顺序
    }

    public boolean headerIsClosed(){
        if(headerBehavior == null)
            return false;
        return headerBehavior.isClosed();
    }
    public void openHeader(){
        try {
            ((CommNewsFragment) fragments.get(viewPage.getCurrentItem())).scrollToStart();
        } catch (Exception e){} finally {
            if(headerBehavior != null)
                headerBehavior.openPager();
        }
    }
    public void closeHeader(){
        if(headerBehavior != null)
            headerBehavior.closePager();
    }

    @Override
    public void onRefreshFinish(String typeId) {
        if(typeId.equals(homePageView.getTag())) {
            homePageView.dataRefreshFinish();
            homePageView.setTag(null);
        }
    }

    private OnBebaviorListener bebaviorListener;
    public void setOnBebaviorListener(OnBebaviorListener bebaviorListener){
        this.bebaviorListener = bebaviorListener;
    }
    public interface OnBebaviorListener{
        void onBebaviorOpen();
        void onBebaviorClose();
    }
}
